//
//  ImageHandler.m
//  OpenCV-AnimalRecognize
//
//  Created by wjj on 14-10-27.
//  Copyright (c) 2014年 wjj. All rights reserved.
//

#import "ImageHandler.h"

using namespace cv;

@implementation ImageHandler

static UIImage* MattoUIImage(const cv::Mat& m)
{
    //CV_ASSERT(m.depth() == CV_8U);
    if (m.depth() !=CV_8U)
        return nil;
    NSData* data = [NSData dataWithBytes:m.data length:m.elemSize()*m.total()];
    CGColorSpaceRef colorSpace = m.channels() ==1 ? CGColorSpaceCreateDeviceGray():CGColorSpaceCreateDeviceRGB();
    CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
    // Creating CGImage from cv::Mat®
    CGImageRef imageRef = CGImageCreate(m.cols, m.rows, m.elemSize1()*8, m.elemSize()*8, m.step[0], colorSpace, kCGImageAlphaNoneSkipFirst|kCGBitmapByteOrderDefault, provider, NULL, false, kCGRenderingIntentDefault);
    UIImage* finalImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    CGDataProviderRelease(provider);
    CGColorSpaceRelease(colorSpace);
    return  finalImage;
}

// convert UIImage to cv::Mat
static void UIImagetoMat(const UIImage* image, cv::Mat& m)
{
    CGColorSpaceRef colorSpace = CGImageGetColorSpace(image.CGImage);
    CGFloat cols = image.size.width;
    CGFloat rows = image.size.height;
    m.create(rows, cols, CV_8UC4);
    
    CGContextRef contextRef = CGBitmapContextCreate(m.data, cols,rows, 8, m.step[0], colorSpace, kCGImageAlphaNoneSkipLast|kCGBitmapByteOrderDefault);
    
    CGContextDrawImage(contextRef, CGRectMake(0, 0, cols, rows), image.CGImage);
    
    CGContextRelease(contextRef);
    CGColorSpaceRelease(colorSpace);
}

- (UIImage *)mergeImage:(UIImage *)firstImage :(CGFloat)firstWeight :(UIImage *)secondImage :(CGFloat)secondWeight
{
    UIImage *image = nil;
//    Mat image0=imread("lion.png",CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR);//载入最真实的图像
//    ge1=imread("dota.jpg",0);//载入灰度图
    Mat image2=imread("tiger.png",199);//载入3通道的彩色图像
    Mat logo=imread("lion.png");//载入3通道的彩色图像
    
    return image;
}

@end
